import mysql.connector
from mysql.connector import Error

# 数据库配置
dbconfig = {
    "host": "localhost",
    "user": "root",
    "password": "ccav20031028cctv",
    "database": "rehab_system",
    "autocommit": False  # 改为手动事务控制
}

class DatabaseManager:
    def __init__(self, dbconfig):
        self.config = dbconfig
        self.connection = self.connect()
        self.cursor = self.connection.cursor(dictionary=True)

    def connect(self):
        """建立带重试机制的数据库连接"""
        try:
            return mysql.connector.connect(**self.config)
        except Error as err:
            print(f"数据库连接失败: {err}")
            raise

    def execute_query(self, query, params=None, commit=False):
        """执行SQL查询"""
        try:
            self.cursor.execute(query, params)
            if commit:
                self.connection.commit()
            return self.cursor.fetchall()
        except Error as err:
            self.connection.rollback()
            print(f"执行查询失败: {err}")
            return None

    def close(self):
        """关闭数据库连接"""
        try:
            self.cursor.close()
            self.connection.close()
        except Error as err:
            print(f"关闭连接失败: {err}")



